package com.waylent.todolist;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.waylent.todolist.entity.Task;
import com.waylent.todolist.entity.Task_;
import com.yalantis.beamazingtoday.interfaces.AnimationType;
import com.yalantis.beamazingtoday.interfaces.BatModel;
import com.yalantis.beamazingtoday.listeners.BatListener;
import com.yalantis.beamazingtoday.listeners.OnItemClickListener;
import com.yalantis.beamazingtoday.listeners.OnOutsideClickedListener;
import com.yalantis.beamazingtoday.ui.adapter.BatAdapter;
import com.yalantis.beamazingtoday.ui.animator.BatItemAnimator;
import com.yalantis.beamazingtoday.ui.callback.BatCallback;
import com.yalantis.beamazingtoday.ui.widget.BatRecyclerView;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;

public class TaskFragment extends Fragment {

    public static final int TYPE_TODAY = 0;
    public static final int TYPE_BIG_EVENG = 1;
    public static final int TYPE_CUSTOM = 2;
    public static final int TYPE_DREAM = 3;

    private BatRecyclerView mRecyclerView;
    private BatAdapter mAdapter;
    private List<BatModel> mGoals = new ArrayList<>();
    private BatItemAnimator mAnimator;
    private Box<Task> taskDB;
    private int type;

    public static TaskFragment newInstance(int type) {
        TaskFragment fragment = new TaskFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        type = getArguments().getInt("type");

        View rootView = inflater.inflate(R.layout.task_fragment, container, false);

        //BatRecyclerView是对官方RecyclerView的封装
        mRecyclerView = (BatRecyclerView) rootView.findViewById(R.id.bat_recycler_view);

        initRecyclerView();

        mRecyclerView.setAddItemListener(batListener);
        mRecyclerView.setDividerColor(getResources().getColor(R.color.background));
        mRecyclerView.setPlusColor(getResources().getColor(R.color.text));
        mRecyclerView.setRadioButtonColor(getResources().getColor(R.color.text));
        mRecyclerView.setHint("请输入");
        mRecyclerView.setHintColor(getResources().getColor(R.color.hint));

        rootView.setOnClickListener(onOtherAreaClickListener);

        return rootView;
    }

    public void setFocusToHead(){
        mRecyclerView.setFocusToHead();
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = mRecyclerView.getView();
        //设置布局
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置数据
        initAdapter();
        recyclerView.setAdapter(mAdapter);
        //设置操作效果
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(batListener));
        itemTouchHelper.attachToRecyclerView(recyclerView);
        //设置动画效果
        recyclerView.setItemAnimator(mAnimator);
    }

    private void initAdapter() {
        mAnimator = new BatItemAnimator();
        initData();
        mAdapter = new BatAdapter(mGoals, batListener, mAnimator)
                .setOnItemClickListener(onItemClickListener)
                .setOnOutsideClickListener(onOutsideClickedListener);
    }

    /**
     * 从数据库读取上一次的数据
     */
    private void initData() {
        if (mGoals.size() == 0) {
            taskDB = ((App) getActivity().getApplication()).getBoxStore().boxFor(Task.class);
            List<Task> tasks = taskDB.query()
                    .equal(Task_.type, this.type)
                    .equal(Task_.isDelete, false)
                    .order(Task_.order)
                    .order(Task_.isChecked)
                    .build().find();
            mGoals.addAll(tasks);
        }
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onClick(BatModel item, int position) {

        }
    };

    /**
     * 增删改RecyclerView的Item时的回调
     */
    private BatListener batListener = new BatListener() {
        @Override
        public void add(String string) {
            for (BatModel item : mGoals) {
                item.setOrder(item.getOrder() + 1);
            }
            Task task = new Task();
            task.name = string;
            task.type = type;
            task.order = 0;
            mGoals.add(0, task);
            mAdapter.notify(AnimationType.ADD, 0);
            //对数据库执行同样的操作
            List<Task> taskList = taskDB.query().equal(Task_.type, TaskFragment.this.type).build().find();
            for (Task item : taskList) {
                item.order++;
            }
            taskDB.put(taskList);
            taskDB.put(task);

        }

        @Override
        public void delete(int position) {
            Task task = (Task) mGoals.get(position);
            mGoals.remove(position);
            mAdapter.notify(AnimationType.REMOVE, position);
            List<Task> tasks = taskDB.query().equal(Task_.type, TaskFragment.this.type).greater(Task_.order, task.order).build().find();
            for (Task item : tasks) {
                item.order--;
            }
            taskDB.put(tasks);
            taskDB.remove(task);
        }

        @Override
        public void move(int from, int to) {
            if (from >= 0 && to >= 0) {
                mAnimator.setPosition(to);
                BatModel model = mGoals.get(from);
                mGoals.remove(model);
                mGoals.add(to, model);
                mAdapter.notify(AnimationType.MOVE, from, to);
                //数据库进行响应操作
                List<Task> toTask = taskDB.query().equal(Task_.type, TaskFragment.this.type).equal(Task_.order, to).build().find();
                toTask.get(0).order = from;
                taskDB.put(toTask);
                Task task = (Task) model;
                task.order = to;
                taskDB.put(task);

                if (from == 0 || to == 0) {
                    mRecyclerView.getView().scrollToPosition(Math.min(from, to));
                }
            }
        }

        @Override
        public void setChecked(BatModel model, int from, int to) {
            if (from >= 0 && to >= 0) {
                mAnimator.setPosition(to);
                mGoals.remove(model);
                mGoals.add(to, model);
                mAdapter.notify(AnimationType.MOVE, from, to);

                if (from == 0 || to == 0) {
                    mRecyclerView.getView().scrollToPosition(Math.min(from, to));
                }
            }
            if (to > from) {
                Task task = (Task) model;
                task.order = mGoals.size() - 1;
                List<Task> tasks = taskDB.query().equal(Task_.type, TaskFragment.this.type).greater(Task_.order, from).build().find();
                for (Task item : tasks) {
                    item.order--;
                }
                taskDB.put((Task) model);
                taskDB.put(tasks);
            } else {
                List<Task> tasks = taskDB.query().equal(Task_.type, TaskFragment.this.type).less(Task_.order, from).build().find();
                for (Task item : tasks) {
                    item.order++;
                }
                Task task = (Task) model;
                task.order = 0;
                taskDB.put((Task) model);
                taskDB.put(tasks);
            }
        }
    };

    private OnOutsideClickedListener onOutsideClickedListener = new OnOutsideClickedListener() {
        @Override
        public void onOutsideClicked() {
            mRecyclerView.revertAnimation();
        }
    };

    private View.OnClickListener onOtherAreaClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mRecyclerView.revertAnimation();
        }
    };
}
